﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Fuse8.ContentManagementFramework.Domain.Commands;
using Fuse8.DomainFramework.Common.Locator;
using Fuse8.DomainFramework.DataAccess;
using Fuse8.DomainFramework.DataAccess.SqlDatabase;
using Fuse8.DomainFramework.Domain;

namespace Fuse8.ContentManagementFramework.DataAccess.SqlAccess.Commands
{
    internal class CmsEntitySearchDataCommand<TEntity> : CmsEntitySearchCommand<TEntity> where TEntity : Int32EntityObject, new()
    {
        public CmsEntitySearchDataCommand()
        {
            StoredProcBaseName = "cms_sp_EntitySearch";
        }

        public string StoredProcBaseName { get; set; }

        public override IQueryable<TEntity> Execute()
        {
            IEnumerable<TEntity> documents = null;

            var factory = DependencyServiceLocator.Current.GetInstance<IUnitOfWorkFactory<TEntity>>();
            var currentUnitOfWork = factory.Get(false) as SqlUnitOfWork<TEntity>;
            if (currentUnitOfWork != null)
            {
                var mapper = DependencyServiceLocator.Current.GetInstance<ISqlEntityDataMapper<TEntity, int>>();
                documents = SqlUtility<TEntity, int>.ExecuteReader(
                        currentUnitOfWork.Connection,
                        currentUnitOfWork.Transaction,
                        StoredProcBaseName + typeof(TEntity).Name,
                        new
                        {
                            CommandParameter.SearchQuery,
                            CommandParameter.IsInAdministrationArea,
                            CommandParameter.SiteGroupId,
                            CommandParameter.SiteId
                        },
                        mapper);
            }
            return documents != null ? documents.AsQueryable() : new List<TEntity>().AsQueryable();
        }
    }

}
